from dash import Input, Output, State, callback_context, no_update, ALL,html
from models import db, RepairRecord
from datetime import datetime
import dash
import base64
import os

#  # 引入Modal组件
# from modules.repair.modals import  register_modal_callbacks

# # 注册Modal相关的回调
# register_modal_callbacks(dash_app)

def register_repair_complete_callbacks(dash_app):
    # 打开维修响应模态窗口并带出信息
    @dash_app.callback(
        Output("repair-complete-modal", "is_open"),
        Output("repair-complete-info", "children"),
        # Output("repair-complete-person", "value"),
        # Output("repair-complete-company", "value"),
        # Output("repair-complete-expected-date", "date"),
        # Output("repair-complete-remarks", "value"),
        Output("repair-complete-alert", "is_open"),
        Output("repair-complete-alert", "children"),
        Input("repair-complete-button", "n_clicks"),  # 只监听右下角按钮
        State("repair-records-table", "data"),
        State("repair-details-record-id-store", "data"),  # 需要知道当前选中的记录id
        prevent_initial_call=True
    )
    def open_repair_complete_modal(n_clicks, table_data, record_id):
        if not n_clicks or n_clicks == 0: 
            print(f"callbacks3 P32 n_clicks:{n_clicks}")
            return dash.no_update, dash.no_update, dash.no_update, dash.no_update
        if not n_clicks or not record_id:
            print(f"callbacks3 P33 n_clicks:{n_clicks},record_id:{record_id}")
            return dash.no_update, dash.no_update, dash.no_update, dash.no_update
        # 查找该条记录
        record = next((r for r in table_data if r["id"] == record_id), None)
        if not record:
            print(f"callbacks3 P37 n_clicks:{n_clicks},record:{record}")
            return dash.no_update, "未找到维修记录", True, "未找到维修记录"
        from models import Product  # 确保导入 Product
        ctx = callback_context
        if not ctx.triggered:
            # raise dash.exceptions.PreventUpdate
            print("call3 p41 callbacks2 P15 ctx.triggered: ",ctx.triggered)
        # 找到被点击的按钮index
        btn_id = ctx.triggered[0]["prop_id"].split(".")[0]
        try:
            record_id = int(eval(btn_id)["index"])
        except Exception:
            return no_update, no_update,  True, "无法识别维修记录ID"
        # 查找该条记录
        record = next((r for r in table_data if r["id"] == record_id), None)
        print(f'callbacks2 P32 record:{record}')
        if not record:
            return no_update, no_update, True, "未找到维修记录"
        # 用 product_id 查 Product 表
        product_id = record.get("product_id")
        print(f'callbacks2 P37 product_id:{product_id},record:{record}')
        product_info = None
        if product_id:
            product = db.session.query(Product).filter_by(id=product_id).first()
            if product:
                product_info = [
                    html.Div(f"设备详细信息："),
                    html.Div(f"设备ID: {product.id}"),
                    html.Div(f"设备名称: {product.product_name}"),
                    html.Div(f"设备编号: {product.product_code}"),
                    html.Div(f"品牌: {getattr(product, 'manufacturer', '')}"),
                    html.Div(f"型号: {getattr(product, 'model', '')}"),
                    html.Div(f"机构: {getattr(product, 'org_short_name_c', '')}"),
                    html.Div(f"科室: {getattr(product, 'department_name', '')}"),
                    html.Div(f"采购日期: {product.purchase_date.strftime('%Y-%m-%d') if product.purchase_date else ''}"),
                    # html.Div(f"价格: {product.price}"),
                    html.Div(f"运行状态: {getattr(product, 'running_status', '')}"),
                ]
            else:
                product_info = [html.Div("未找到设备详细信息")]
        else:
            product_info = [html.Div("无设备ID，无法查询设备信息")]

        # 展示信息（维修单信息 + 设备详细信息）
        info = html.Div([
            html.Div(f"维修单号: {record['id']}"),
            html.Div(f"设备ID: {record.get('product_id', '')}"),
            html.Div(f"设备名称: {record.get('product_name', '')}"),
            html.Div(f"设备编号: {record.get('product_code', '')}"),
            # html.Div(f"品牌: {record.get('product_brand', '')}"),
            # html.Div(f"型号: {record.get('product_model', '')}"),
            html.Div(f"机构: {record.get('org_name', '')}"),
            html.Div(f"科室: {record.get('department_name', '')}"),
            html.Div(f"故障描述: {record.get('fault_description', '')}"),
            html.Div(f"报修时间: {record.get('report_date', '')}"),
            html.Div(f"报修人: {record.get('repair_caller', '')}"),
            html.Hr(),
            *product_info
        ],style={"marginTop": "80px"})
        # return True, info, "", "", None, "", False, ""
        return True, info, False, ""

    # 关闭模态窗口
    @dash_app.callback(
        Output("repair-complete-modal", "is_open", allow_duplicate=True),
        Input("repair-complete-cancel", "n_clicks"),
        prevent_initial_call=True
    )
    def close_repair_respond_modal(n_cancel):
        if n_cancel:
            return False
        return no_update

    # 提交维修完成
    @dash_app.callback(
        Output("repair-complete-modal", "is_open", allow_duplicate=True),
        Output("repair-complete-alert", "is_open", allow_duplicate=True),
        Output("repair-complete-alert", "children", allow_duplicate=True),
        Input("repair-complete-confirm", "n_clicks"),
        # State("repair-complete-person", "value"),
        # State("repair-complete-company", "value"),
        
        # State("repair-complete-remarks", "value"),
        # State("repair-complete-info", "children"),
        prevent_initial_call=True
    )
    def submit_repair_complete(n_submit, person, company, expected_date, remarks, info_children):
        print("call3, p114 submit_repair_complete called")
        print(f"info_children: {info_children}")
        if not n_submit:
            # raise dash.exceptions.PreventUpdate
            print(f"call3, p126 submit_repair_complete called")
        try:
            record_id = None
            # info_children 可能是 dict（html.Div）或 list
            children = info_children.get("props", {}).get("children", []) if isinstance(info_children, dict) else info_children
            for child in children:
                # child 可能是 dict 或 str
                text = ""
                if isinstance(child, dict):
                    text = child.get("props", {}).get("children", "")
                elif isinstance(child, str):
                    text = child
                if "维修单号" in text:
                    record_id = int(text.split(":")[1].strip())
                    break
            print(f"parsed record_id: {record_id}")
            if not record_id:
                return no_update, True, "无法获取维修单号"
        except Exception as e:
            print(f"解析维修单号异常: {e}")
            return no_update, True, "无法解析维修单号"
        # 校验
        # if not person or not company or not expected_date:
        #     return no_update, True, "请填写所有必填项"
        # 更新数据库
        record = db.session.query(RepairRecord).filter_by(id=record_id).first()
        print(f"callbacks3 P142 record:{record}")
        if not record:
            return no_update, True, "未找到维修记录"
        record.repair_person = person
        record.repair_company = company
        record.expected_completion_date = datetime.strptime(expected_date, "%Y-%m-%d").date()
        record.remarks = remarks
        record.repair_status = "维修完成"
        db.session.commit()
        return False, False, ""

   

    
    